package com.only4play.auth.security.config;

import com.only4play.auth.security.entrypoint.CustomerAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;

import static com.only4play.auth.security.authentication.admin.sms.AdminSmsConfigure.adminSmsLogin;
import static com.only4play.auth.security.authentication.admin.password.AdminPasswordConfigure.adminPasswordLogin;

/**
 * @author zlm
 * @date 2024/1/22
 */
@EnableWebSecurity
@Configuration
public class SecurityConfig {


  /**
   * 用户登陆
   * @param http
   * @return
   * @throws Exception
   */
  @Bean
  public SecurityFilterChain userLoginFilterChain(HttpSecurity http) throws Exception {


    return http.build();
  }

  /**
   * 后台登陆
   * @param http
   * @return
   * @throws Exception
   */
  @Bean
  public SecurityFilterChain adminLoginFilterChain(HttpSecurity http) throws Exception {
    //拦截路径
    http.antMatcher("/admin/**");
    http.apply(adminPasswordLogin());
    http.apply(adminSmsLogin());
    http.csrf().disable();
    //对session处理
    http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    //登陆异常处理
    http.exceptionHandling(exception -> {
      //未登录处理
      exception.authenticationEntryPoint(authenticationEntryPoint());
      //未授权处理
      //exception.accessDeniedHandler();
    });

    http.authorizeRequests( request -> request.antMatchers("/admin/**").permitAll());


    return http.build();
  }

  @Bean
  public AuthenticationEntryPoint authenticationEntryPoint(){
    return new CustomerAuthenticationEntryPoint();
  }

}
